App({
  globalData: {
    city1: '',//司机常用提货地址
    city2: '',//司机常用卸货地址
  },
  // 小程序初始化
  onLaunch: function () {

    // 检查登录态
    this.checkSession();
    // 缓存用户信息
    this.getUserInfo();
  },

  // 检查登录态
  checkSession: function () {
    var that = this;
    wx.checkSession({

      // 有效
      success: function () {
        //（检测有效且有3rd_session的storage，直接拿，不再请求接口）
        that.getLoginSession(function (res) {
          console.log(res);
          console.log('本地存储3rd_session为：' + res);
        })
      },

      // 失效
      fail: function () {
        that.login();
      }
    })
  },

  // 获取localStorage中的3rd_session，需要登录授权的接口使用
  getLoginSession: function (fn) {
    var that = this;
    wx.getStorage({
      key: 't_session',
      success: function (res) {

        // 有直接执行回调
        typeof fn == 'function' && fn(res.data);
        console.log('从localStorage中拿'+res.data);
      },
      fail: function () {

        // 没有再次登录拿3rd_session
        that.login(function (res) {
          typeof fn == 'function' && fn(res);
          console.log('从登录接口拿');
        })
      }
    })
  },
//获取用户身份
  getLoginRole: function (fn) {
    var that = this;
    wx.getStorage({
      key: 'role',
      success: function (res) {

        // 有直接执行回调
        typeof fn == 'function' && fn(res.data);
        console.log('从localStorage中拿' + res.data);
      },
      fail: function () {

        // 没有再次登录拿3rd_session
        that.login(function (res) {
          typeof fn == 'function' && fn(res);
          console.log('从登录接口拿');
        })
      }
    })
  },

  // 用户登录
  login: function (fn) {
    var that = this;
    wx.login({
      success: function (res) {

        console.log('本地登录成功');
        console.log(res);
        if (res.code) {
          wx.request({
            url: that.api +'/wx_log_test/app/login',
            data: {
              code: res.code
            },
            success: function (result) {
              console.log(that.api+'/wx_log_test/app/login?code='+res.code);
              console.log(result);
              var session = result.data.data.token;
              var role = result.data.data.role;
              console.log(session);
              // 存储3rd_session
              wx.setStorage({
                key: "t_session",
                data: session,
                success: function () {
                  console.log('存储session成功');
                  typeof fn == 'function' && fn(session);
                },
                fail: function () {
                  console.log('存储session失败');
                }
              })
              //储存用户身份
              wx.setStorage({
                key: "role",
                data: role,
                success: function () {
                  console.log('存储role成功');
                  typeof fn == 'function' && fn(role);
                },
                fail: function () {
                  console.log('存储role失败');
                }
              })
            }
          })

        } else {
          wx.showModal({
            title: '提示',
            content: '获取用户登录态失败！是否重新获取？',
            cancelText: '否',
            confirmText: '是',
            success: function (res) {
              if (res.confirm) {
                 that.login();
              }
            }
          })
        }
      }
    });

  },

  // 获取用户信息
  getUserInfo: function (fn) {
    var that = this
    if (that.userInfo) {
      console.log("dskljflsjflsjdfljsogjwrsogfosdg");
      console.log(that.userInfo);
      that.updateUserInfo(that.userInfo);
      typeof fn == "function" && fn(that.userInfo)
    } else {
      console.log("SDFSFSDSDdskljflsjflsjdfljsogjwrsogfosdg");
      wx.login({
        success: function () {
          console.log("SDFSFSDSDdskljflsjflsjdfljsogjwrsogfosdg");
          wx.getUserInfo({
            success: function (res) {
              console.log("SDFSFSDSDdskljflsjflsjdfljsogjwrsogfosdg");
              console.log(res);
              that.updateUserInfo(res);
              typeof fn == "function" && fn(res);
            },
            fail: function () {
              wx.showModal({
                title: '警告',
                content: '若不授权微信登录，则无法正常使用小程序；点击确定重新获取授权，则可重新使用；若点击取消，后期还使用小程序，需要在微信【发现】——【小程序】——删掉【鸡小贱】，重新搜索授权登录，方可使用',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                    wx.openSetting({
                      success: function (res) {
                        if (!res.authSetting["scope.userInfo"] || !res.authSetting["scope.userLocation"]) {
                          //这里是授权成功之后 填写你重新获取数据的js
                          //参考:
                          that.getLogiCallback('', function () {
                            callback('')
                          })
                        }
                      }
                    })
                  } else {
                    console.log('用户点击取消')
                  }

                }
              })
            }
          })
        }
      })
    }
  },

  // 提交用户信息
  updateUserInfo: function (info) {
    var that = this;
    console.log(info);
    console.log("owrefoiejrghdfodog");
    if (info) {
      console.log(info);
      that.getLoginSession(function (session) {
        wx.request({
          url: that.api + '/wx_log_test/app/checkinfo',
          data: {
            encryptedData: info.encryptedData,
            iv: info.iv,
            rawData: info.rawData,
            signature: info.signature,
            token: session
          },
          success: function (result) {
            console.log(result.data);
          }
        })
      });
    }
  },

  // 获取支付信息
  callToPay: function (orderId, amount, store_id, fn) {

    var that = this;

    if (isNaN(orderId)) {
      return
    }

    that.getLoginSession(function (session) {
      // 请求
      wx.request({

        // 请求地址
        url: that.api,

        // 请求参数
        data: {
          app: 'cashier',
          act: 'index',
          order_id: orderId,
          t_session: session
        },

        // 请求成功
        success: function (res) {
          var data = res.data;
          if (data.done && data.retval) {
            var result = data.retval;
            console.log(result);

            // 优惠券抵消为0时直接到成功页
            if (amount == 0 && result.isPay && result.isPay == 1) {
              wx.navigateTo({
                url: '/pages/paySuccess/paySuccess?store_id=' + store_id,
              })
              return
            }
            // 唤起支付功能
            wx.requestPayment({
              'timeStamp': result.timeStamp,
              'nonceStr': result.nonceStr,
              'package': result.package,
              'signType': 'MD5',
              'paySign': result.paySign,
              'success': function (res) {
                console.log(res);
                wx.redirectTo({
                  url: '/pages/paySuccess/paySuccess?store_id=' + store_id,
                })
              },
              'fail': function (res) {
                console.log(res);
                wx.showModal({
                  title: '提示',
                  showCancel: false,
                  content: '支付失败'
                })
              }
            });
          } else {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '获取支付信息失败'
            })
          }
        }
      })

    })
  },


  
  turn: function (list) {//对下标重新赋值下标从0开始
    var arr = [];
    for (var i in list) {
      var str = list[i]
      arr.push(str);
    }
    list = arr;
    return list
  },

  // 存储用户信息
  userInfo: null,

  // 连续重复登录次数
  reLoginNum: 3,

  // 统一错误提示
  errorTips: '数据加载中...',

  // cdn静态文件地址(假装它是CDN)
  cdn: 'https://www.gzgaodu.com/static/',

  // 接口地址
  api: 'https://tmsapp.circlelog.com'
  

});